package com.jsbs.iam.common.core.component;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class BasicContext {
    private InheritableThreadLocal<Map<String, Object>> inheritableThreadLocal = new InheritableThreadLocal<Map<String, Object>>() {
        @Override
        protected Map<String, Object> childValue(Map<String, Object> parentValue) {
            if (parentValue == null) {
                return null;
            }
            return new HashMap<String, Object>(parentValue);
        }
    };

    public void put(String key, Object val) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Map<String, Object> map = inheritableThreadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            inheritableThreadLocal.set(map);
        }
        map.put(key, val);
    }

    public Object get(String key) {
        Map<String, Object> map = inheritableThreadLocal.get();
        if ((map != null) && (key != null)) {
            return map.get(key);
        } else {
            return null;
        }
    }

    public void clear() {
        Map<String, Object> map = inheritableThreadLocal.get();
        if (map != null) {
            map.clear();
            inheritableThreadLocal.remove();
        }
    }
}
